package com.yx.changdao.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yx.changdao.common.data.RespCodeEnum;
import com.yx.changdao.common.data.ResultCodeEnum;
import com.yx.changdao.common.entity.*;
import com.yx.changdao.common.utils.*;
import com.yx.changdao.common.vo.BuildBuildVo;
import com.yx.changdao.common.vo.DownCommunityBuildVo;
import com.yx.changdao.service.*;
import com.yx.changdao.common.annotation.AutoLog;
import com.yx.changdao.common.annotation.ShiroDesc;
import com.yx.changdao.common.data.Result;
import com.yx.changdao.common.exception.AlertException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.POST;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @Description: <br/>
 * 社区建筑物表
 * <p>
 * <br/>
 * @Auther: walter
 * @create 2020/04/02 14:20
 */
@Validated
@RestController
@RequestMapping("community/build")
public class CommunityBuildController {
    @Autowired
    private CommunityResidentService communityResidentService;
    /**
     * 社区建筑物表服务
     */
    @Autowired
    private CommunityBuildService communityBuildService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private GridInfoService gridInfoService;
    @Autowired
    private CommunityBuildDetailService communityBuildDetailService;
    @Autowired
    private SysUserService sysUserService;
    /**
     * 建筑物联户组关联服务
     */
    @Autowired
    private ContactGroupBuildService contactGroupBuildService;
    /**
     * 列表
     *
     * @return Result
     */
    @AutoLog("建筑列表")
    @GetMapping("/list")
    public Result list() throws AlertException {
        return Result.ok().data(communityBuildService.list(SysUtils.autoCnd(CommunityBuild.class).orderByDesc(CommunityBuild.CREATE_TIME)));
    }


    /**
     * 添加社区建筑物表
     *
     * @param
     * @return Result
     */
    @AutoLog
    @PostMapping
    @Transactional(rollbackFor = {Exception.class})
    public Result add(@RequestBody @Valid CommunityBuild communityBuild) throws AlertException {
        if (communityBuild.getBuildType() == 0) {
            if (Strings.isBlank(communityBuild.getBuildName())) {
                throw new AlertException("楼宇/平房不能为空");
            }
            CommunityBuild one = communityBuildService.getOne(new QueryWrapper<CommunityBuild>()
                    .eq(CommunityBuild.GRID_ID, communityBuild.getGridId())
                    .eq(CommunityBuild.BUILD_NAME, communityBuild.getBuildName()));
            if (one != null) {
                throw new AlertException(one.getBuildName() + "已存在");
            }
        } else {
            if (Strings.isBlank(communityBuild.getShopName())) {
                throw new AlertException("商铺名称名称不能为空");
            }
            CommunityBuild one = communityBuildService.getOne(new QueryWrapper<CommunityBuild>()
                    .eq(CommunityBuild.GRID_ID, communityBuild.getGridId())
                    .eq(CommunityBuild.SHOP_NAME, communityBuild.getShopName()));
            if (one != null) {
                throw new AlertException(one.getShopName() + "已存在");
            }
            if (Strings.isNotBlank(communityBuild.getLinkIdCard())) {
                if (communityBuild.getLinkIdCard().length()!=15&&communityBuild.getLinkIdCard().length()!=18) {
                    throw new AlertException("身份证不合法");
                }
            }
        }
        if (communityBuild.getDepId() == null) {
            String userId = SysUtils.currentUserId();
            SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.USER_ID, userId));
            if (sysUser == null) {
                throw new AlertException("该帐号不存在");
            }
            Department department = departmentService.
                    getOne(new QueryWrapper<Department>().eq(Department.DEP_ID, sysUser.getDepId()));
            communityBuild.setDepId(sysUser.getDepId());
            communityBuild.setDepName(department.getDepName());
        }else {
            Department department = departmentService.
                    getOne(new QueryWrapper<Department>().eq(Department.DEP_ID, communityBuild.getDepId()));
            if(department==null){
                throw new AlertException("该部门不存在");
            }
            communityBuild.setDepId(department.getDepId());
            communityBuild.setDepName(department.getDepName());
        }


        /*if (Strings.isNotBlank(communityBuild.getContactPhone())) {
            boolean matches = communityBuild.getContactPhone().matches("^1[0-9]{10}$");
            if (matches == false) {
                throw new AlertException("请输入正确的手机号码");
            }
        }*/

        boolean b = communityBuildService.save(communityBuild);
        if (!b) {
            throw new AlertException("社区建筑物添加失败");
        }
        communityBuild.setBuildCode(communityBuild.getGridId() + "-" + communityBuild.getId());
        boolean b1 = communityBuildService.updateById(communityBuild);
        if (!b1) {
            throw new AlertException("社区建筑物添加失败");
        }

        CommunityBuild one = communityBuildService.getOne(new QueryWrapper<CommunityBuild>()
                .eq(CommunityBuild.BUILD_CODE, communityBuild.getBuildCode()));
        BuildBuildVo buildBuildVo = new BuildBuildVo();
        buildBuildVo.setId(one.getId());
        buildBuildVo.setName(one.getBuildType() == 0 ? one.getBuildName() : one.getShopName());
        return Result.ok("社区建筑物添加成功").data(buildBuildVo);
    }


    /**
     * 获得指定id 社区建筑物表。
     *
     * @param
     * @return Result
     */
    @AutoLog
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") String id) throws AlertException {
        CommunityBuild communityBuild = communityBuildService.getById(id);
        communityBuild.setLinkIdCard(DesensitizationUtils.idEncrypt(communityBuild.getLinkIdCard()));
        if (communityBuild == null) {
            throw new AlertException("未找到相关社区建筑物信息");
        }

        return Result.ok().data(communityBuild);
    }


    /**
     * 更新社区建筑物表
     *
     * @param
     * @return Result
     */
    @AutoLog
    @PutMapping
    public Result update(@RequestBody @Valid CommunityBuild communityBuild) throws AlertException {
        CommunityBuild communityBuildServiceOne = communityBuildService.getOne(new QueryWrapper<CommunityBuild>().eq(CommunityBuild.ID, communityBuild.getId()));

        if (communityBuild.getBuildType() == 0) {
            if (Strings.isBlank(communityBuild.getBuildCode())) {
                throw new AlertException("楼编号不能为空");
            }
            if (Strings.isBlank(communityBuild.getBuildName())) {
                throw new AlertException("楼宇/平房不能为空");
            }
            CommunityBuild list = communityBuildService.getOne(new QueryWrapper<CommunityBuild>().eq(CommunityBuild.BUILD_CODE, communityBuild.getBuildCode()));
            if (list != null && !list.getId().equals(communityBuild.getId())) {
                throw new AlertException("该楼编号已存在");
            }
            CommunityBuild one = communityBuildService.getOne(new QueryWrapper<CommunityBuild>()
                    .eq(CommunityBuild.GRID_ID, communityBuildServiceOne.getGridId())
                    .eq(CommunityBuild.BUILD_NAME, communityBuild.getBuildName()));
            if (one != null && !one.getId().equals(communityBuild.getId())) {
                throw new AlertException(one.getBuildName() + "已存在");
            }


        } else {
            if (Strings.isBlank(communityBuild.getShopName())) {
                throw new AlertException("商铺名称名称不能为空");
            }
            if (Strings.isNotBlank(communityBuild.getLinkIdCard())) {

                if (communityBuild.getLinkIdCard().length()!=15&&communityBuild.getLinkIdCard().length()!=18) {
                    throw new AlertException("身份证不合法");
                }
            }
            CommunityBuild one = communityBuildService.getOne(new QueryWrapper<CommunityBuild>()
                    .eq(CommunityBuild.GRID_ID, communityBuild.getGridId())
                    .eq(CommunityBuild.SHOP_NAME, communityBuild.getShopName()));
            if (one != null && !one.getId().equals(one.getId())) {
                throw new AlertException(one.getShopName() + "已存在");
            }

        }

        if (communityBuild.getDepId() == null) {
            String userId = SysUtils.currentUserId();
            SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.USER_ID, userId));
            if (sysUser == null) {
                throw new AlertException("该帐号不存在");
            }
            Department department = departmentService.
                    getOne(new QueryWrapper<Department>().eq(Department.DEP_ID, sysUser.getDepId()));
            communityBuild.setDepId(sysUser.getDepId());
            communityBuild.setDepName(department.getDepName());
        }else {
            Department department = departmentService.
                    getOne(new QueryWrapper<Department>().eq(Department.DEP_ID, communityBuild.getDepId()));
            if(department==null){
                throw new AlertException("该部门不存在");
            }
            communityBuild.setDepId(department.getDepId());
            communityBuild.setDepName(department.getDepName());
        }

       /* if (Strings.isNotBlank(communityBuild.getContactPhone())) {
            boolean matches = communityBuild.getContactPhone().matches("^1[0-9]{10}$");
            if (matches == false) {
                throw new AlertException("请输入正确的手机号码");
            }
        }*/
        boolean b = communityBuildService.updateById(communityBuild);
        if (!b) {
            throw new AlertException("社区建筑物更新失败");
        }
        List<CommunityResident> list = communityResidentService.list(new QueryWrapper<CommunityResident>().eq(CommunityResident.BUILD_ID, communityBuild.getId()));
        if (list.size() != 0) {
            for (CommunityResident communityResident : list) {
                communityResident.setBuildName(communityBuild.getBuildName());
                communityResidentService.updateById(communityResident);
            }
        }

        return Result.ok("社区建筑物更新成功");
    }


    /**
     * 删除社区建筑物表
     *
     * @param
     * @return Result
     */
    @AutoLog
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = {Exception.class})
    public Result delete(@PathVariable("id") String id) throws AlertException {

        CommunityBuild one = communityBuildService.getOne(new QueryWrapper<CommunityBuild>()
                .eq(CommunityBuild.ID, id));
        BuildBuildVo buildBuildVo = new BuildBuildVo();
        buildBuildVo.setId(one.getId());
        buildBuildVo.setName(one.getBuildType() == 0 ? one.getBuildName() : one.getShopName());

        //删除房
//        boolean b1 = communityBuildService.removeBuildDetail(Integer.parseInt(id));
//        if (!b1) {
//            throw new AlertException("社区建筑物删除失败");
//        }
        List<CommunityBuildDetail> list = communityBuildDetailService.list(new QueryWrapper<CommunityBuildDetail>().eq(CommunityBuildDetail.BUILD_ID, id));
        if (list.size() != 0) {
            return new Result(RespCodeEnum.OK, null, ResultCodeEnum.DELETE, "您删除的层级内包含其他数据信息!", buildBuildVo);
        }

        //删除房
        boolean b = communityBuildService.removeById(id);
        if (!b) {
            throw new AlertException("社区建筑物删除失败");
        }
        return Result.ok("删除社区建筑物成功").data(buildBuildVo);
    }

    /**
     * 根据网格id查建筑
     *
     * @return
     */
    @AutoLog
    @GetMapping("/getBuildByGridId")
    public Result getBuildByGridId(@RequestParam("regionId") Integer regionId) {
        List<CommunityBuild> buildByRegionId = communityBuildService.getBuildByGridId(regionId);
        List<BuildBuildVo> buildBuildVoList = new ArrayList<>();
        for (CommunityBuild communityBuild : buildByRegionId) {
            BuildBuildVo buildBuildVo = new BuildBuildVo();
            buildBuildVo.setId(communityBuild.getId());
            if (communityBuild.getBuildType() != null) {
                if (communityBuild.getBuildType() == 0) {
                    buildBuildVo.setName(communityBuild.getBuildName());
                } else if (communityBuild.getBuildType() == 1) {
                    buildBuildVo.setName(communityBuild.getShopName());
                }
            }
            buildBuildVo.setParent_id(regionId);
            buildBuildVoList.add(buildBuildVo);
        }
        return Result.ok("查询成功").data(buildBuildVoList);
    }

    /**
     * 导入 楼栋
     */
    @AutoLog
    @PostMapping("/checkAndSave")
    public Result checkAndSave(@RequestParam("communityBuild") MultipartFile communityBuild) throws AlertException {
        /**
         * 保存正常的，返回异常的
         */
        Map<String, Object> map = communityBuildService.checkAndSave(communityBuild);
        return Result.ok().data(map);
    }

    /**
     * 导入 商铺
     */
    @AutoLog
    @PostMapping("/checkAndSaveShop")
    public Result checkAndSaveShop(@RequestParam("communityBuildShop") MultipartFile communityBuildShop) throws AlertException {
        /**
         * 保存正常的，返回异常的
         */
        Map<String, Object> map = communityBuildService.checkAndSaveShop(communityBuildShop);
        return Result.ok().data(map);
    }


    @AutoLog
    @GetMapping("/down")
    public void down() throws AlertException, IOException {
        HttpServletResponse response = SysUtils.getResponse();
        List<CommunityBuild> list = communityBuildService.list();
        List<DownCommunityBuildVo> communityBuildVos=new ArrayList<>();
        for (CommunityBuild communityBuild : list) {
            DownCommunityBuildVo communityBuildVo = new DownCommunityBuildVo();
            if(communityBuild.getBuildType()!=null){
                if(communityBuild.getBuildType().equals(0)){
                    communityBuildVo.setBuildName(communityBuild.getBuildName());
                }else {
                    communityBuildVo.setBuildName(communityBuild.getShopName());
                }
            }

            communityBuildVo.setBuildCode(communityBuild.getBuildCode());
            GridInfo byId = gridInfoService.getOne(new QueryWrapper<GridInfo>().eq(GridInfo.ID,communityBuild.getGridId()));
            if(byId!=null){
                communityBuildVo.setGridNum(byId.getGridNum()==null?null:byId.getGridNum());
            }
            communityBuildVos.add(communityBuildVo);
        }
        ExcelImportExportUtils.writeExcel(DownCommunityBuildVo.class, communityBuildVos, response, "楼名/楼编号");
    }

    /**
     * 住宅模板下载
     *
     * @param response
     * @throws AlertException
     * @throws IOException
     */
    @AutoLog
    @GetMapping("/template")
    public void template(HttpServletResponse response) throws AlertException, IOException {
        File cfgFile = ResourceUtils.getFile("classpath:public/住宅统一表头.xlsx");

        Faster.download(response, cfgFile);
    }

    /**
     * 商铺模板下载
     *
     * @param response
     * @throws AlertException
     * @throws IOException
     */
    @AutoLog
    @GetMapping("/templateShop")
    public void templateShop(HttpServletResponse response) throws AlertException, IOException {
        File cfgFile = ResourceUtils.getFile("classpath:public/商铺统一表头.xlsx");

        Faster.download(response, cfgFile);
    }

    /**
     * 对应联户组下的楼栋
     * @param gridId
     * @return
     * @throws AlertException
     */
    @AutoLog
    @GetMapping("/getListByDep")
    public Result getListByDep(@RequestParam("gridId")Integer gridId) throws AlertException {
        String userId = SysUtils.currentUserId();
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.USER_ID, userId));
        if (sysUser == null) {
            return Result.error("该帐号不存在");
        }
        List<BuildBuildVo> buildBuildVoList = new ArrayList<>();
        //获取小组关联的楼
        List<ContactGroupBuild> contactGroupBuilds = contactGroupBuildService.list(new QueryWrapper<ContactGroupBuild>()
                .eq(ContactGroupBuild.CONTACT_GROUP_ID, sysUser.getContactGroupId()));
        if(contactGroupBuilds.size()==0){
            return Result.ok("成功").data(buildBuildVoList);
        }
        //获取该网格下小组关联的楼
        List<CommunityBuild> list = new ArrayList<>();
        for (ContactGroupBuild contactGroupBuild : contactGroupBuilds) {
            CommunityBuild build = communityBuildService.getOne(new QueryWrapper<CommunityBuild>()
                    .eq(CommunityBuild.ID, contactGroupBuild.getBuildId()));
            if(build.getGridId().equals(gridId)&&build.getDepId().equals(sysUser.getDepId())){
                list.add(build);
            }
        }
        for (CommunityBuild communityBuild : list) {
            BuildBuildVo buildBuildVo = new BuildBuildVo();
            buildBuildVo.setId(communityBuild.getId());
            if (communityBuild.getBuildType() != null) {
                if (communityBuild.getBuildType() == 0) {
                    buildBuildVo.setName(communityBuild.getBuildName());
                } else if (communityBuild.getBuildType() == 1) {
                    buildBuildVo.setName(communityBuild.getShopName());
                }
            }
            buildBuildVoList.add(buildBuildVo);
        }
        return Result.ok("成功").data(buildBuildVoList);
    }
    /**
     * 楼栋导入部门信息

     */
    @AutoLog
    @PostMapping("/checkAndSaveDep")
    public Result checkAndSaveDep(@RequestParam("communityBuildDep") MultipartFile communityBuildDep) throws AlertException {
        /**
         * 保存正常的，返回异常的
         */
        Map<String, Object> map = communityBuildService.checkAndSaveDep(communityBuildDep);
        return Result.ok().data(map);
    }
}
